package com.liser.southernstar.utils;

import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;

import androidx.core.content.FileProvider;

import com.liser.southernstar.MainApplication;

import java.io.File;

/**
 * apk工具
 */
public class ApkUtils {

    /**
     * 检查app是否已安装
     */
    public static boolean checkInstalled(String packageName) {
        try {
            return MainApplication.instance().getPackageManager().getPackageInfo(packageName, 0) != null;
        } catch (PackageManager.NameNotFoundException e) {
            return false;
        }
    }

    /**
     * 通过intent安装apk
     *
     * @param file         文件路径，应该指向provider所声明的文件夹
     * @param providerName provider名称
     */
    public static void intentInstall(File file, String providerName) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        Uri uri = FileProvider.getUriForFile(MainApplication.instance(), providerName, file);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        MainApplication.instance().startActivity(intent);
    }
}
